﻿using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;

namespace DataAccess
{
    public class MultipleResultsCommand : DatabaseCommand
    {
        public MultipleResultsCommand()
        {
            _Queries = new Queue<IDatabaseReader>();
        }

        internal Queue<IDatabaseReader> _Queries { get; set; }

        protected override int Execute(DbCommand command)
        {
            int count = 0;

            using (DbDataReader reader = command.ExecuteReader())
            {
                foreach (IDatabaseReader query in _Queries)
                {
                    count += query.Read(reader);

                    reader.NextResult();
                }
            }

            return count;
        }

        protected override async Task<int> ExecuteAsync(DbCommand command)
        {
            int count = 0;

            using (DbDataReader reader = await command.ExecuteReaderAsync())
            {
                foreach (IDatabaseReader query in _Queries)
                {
                    count += query.Read(reader);

                    reader.NextResult();
                }
            }

            return count;
        }

        #region Fluent

        public MultipleResultsCommand Query(IDatabaseReader query)
        {
            _Queries.Enqueue(query);

            return this;
        } 

        #endregion
    }
}
